import React, {Component} from 'react';
import {Image, ScrollView, FlatList, Text, TouchableOpacity, View, AsyncStorage} from 'react-native';
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import Swiper from 'react-native-swiper';
import {BasicStyle} from "../../../style/BasicStyle";
import {ShopStyle} from "../../../style/ShopStyle/ShopStyle";
import FetchUtils from './../../utils/FetchUtils'
import utils from './../../utils/utils';

export default class Shop extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        tabBarLabel: '商城',
        tabBarIcon: ({tintColor, focused}) => (
            focused ?
                <Image style={BasicStyle.tabBarIconImg} resizeMode='contain'
                       source={require('./../../../img/mall_selected.png')}/>
                :
                <Image style={BasicStyle.tabBarIconImg} resizeMode='contain'
                       source={require('./../../../img/mall_no.png')}/>
        ),
        header: null,
    });

    constructor(props) {
        super(props);
        this.state = ({
            swiperShow: false,
            loadingStatus: false,
            bannersView: [],
            typeImgsView: [],
            listData: [],
            lastStatus: false,
            page: 0,
            size: 20,
        })
    }

    componentDidMount() {
        AsyncStorage.getItem("XToken").then((xToken) => {
            let params = {
                page: this.state.page,
                size: this.state.size,
            };
            FetchUtils.getWithHeader(utils.apiUrl + '/shop', xToken, params, (res) => {
                if (res.code === 200) {
                    console.log(res.apiData);
                    this.setState({
                        bannersView: res.apiData.banners.map((item) => {
                            return <TouchableOpacity key={item.id} onPress={() => {
                                let {navigate} = this.props.navigation;
                                navigate('ShopListNav')
                            }}>
                                <Image source={{uri: utils.qiniuUrl + item.resUrl}}
                                       style={BasicStyle.bannerImg}/></TouchableOpacity>
                        }),
                        typeImgsView: res.apiData.types.map((item) => {
                            return <TouchableOpacity key={item.id} onPress={() => {
                                let {navigate} = this.props.navigation;
                                navigate('ShopListNav', {resMark: item.resMark})
                            }}>
                                <Image style={ShopStyle.typeImg} source={{uri: utils.qiniuUrl + item.resUrl}}/>
                            </TouchableOpacity>
                        }),
                        listData: res.apiData.products.content,
                        swiperShow: true,
                        lastStatus: res.apiData.products.last,
                        page: res.apiData.products.number,
                    });
                } else {
                    Toast.showShortTop("错误信息：" + res.apiData);
                }
            })
        })
    }

    render() {
        /*轮播图,防止白图*/
        let mySwiper = this.state.swiperShow ?
            <Swiper horizontal={true} paginationStyle={{bottom: utils.autoWidth(10)}} showsButtons={false}
                    autoplay={true}>
                {this.state.bannersView}
            </Swiper>
            :
            <Image source={require('./../../../img/banner_1.jpg')} style={BasicStyle.bannerImg}/>;
        /*渲染*/
        return (
            <View style={[BasicStyle.containerView, ShopStyle.containerView]}>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    showsHorizontalScrollIndicator={false}
                    removeClippedSubviews={false}
                    onMomentumScrollEnd={this._onScroll.bind(this)}
                >
                    <View style={BasicStyle.bannerView}>
                        {mySwiper}
                    </View>

                    <View style={ShopStyle.typeImgView}>
                        {this.state.typeImgsView}
                    </View>

                    <View style={ShopStyle.listTitleView}>
                        <Text style={ShopStyle.listTitleViewText}>最新上架</Text>
                    </View>
                    <View style={ShopStyle.listView}>
                        {this._makelistItem(this.state.listData)}
                    </View>
                    <Image style={BasicStyle.endImg} source={require('./../../../img/end.png')}/>


                </ScrollView>
            </View>
        );
    }

    /*scrollView滑动方法*/
    _onScroll(event) {
        let y = event.nativeEvent.contentOffset.y;//滑动距离
        let height = event.nativeEvent.layoutMeasurement.height;//scrollView高度
        let contentHeight = event.nativeEvent.contentSize.height;//scrollView contentSize高度
        if (y + height >= contentHeight) {
            AsyncStorage.getItem("XToken").then((xToken) => {
                if (!this.state.lastStatus) {
                    this.setState({loadingStatus: true});
                    let params = {page: this.state.page + 1, size: this.state.size,};
                    FetchUtils.getWithHeader(utils.apiUrl + '/shop/products', xToken, params, (res) => {
                        if (res.code === 200) {
                            this.setState({
                                listData: this.state.listData.concat(res.apiData.products.content),
                                page: res.apiData.products.number,
                                size: res.apiData.products.size,
                                loadingStatus: false,
                            });
                        } else {
                            this.setState({
                                loadingStatus: false,
                            });
                            Toast.showShortTop(res.apiData);
                        }
                    })
                }
            });
        } else {
            this.setState({loadingStatus: false})
        }
    }

    /*生成列表item*/
    _makelistItem(list) {
        let resultList = list.map((item, index) => {
            return <TouchableOpacity key={item.id} onPress={() => {
                let {navigate} = this.props.navigation;
                navigate('ShopDetailNav',{productId: item.id})
            }}
                                     style={[ShopStyle.listItemView, index % 2 === 0 ? {paddingRight: utils.autoWidth(1)} : null]}>
                <Image
                    style={ShopStyle.listItemViewImg}
                    source={{uri: utils.qiniuUrl + item.mainImg + utils.qiniu500Url}}></Image>

                <View style={ShopStyle.listItemTextView}>
                    <Text style={ShopStyle.listTitleViewText}>{item.name}</Text>
                    <View style={{flexDirection: 'row'}}>
                        <Text style={[ShopStyle.listTitleMarkViewText, {
                            textDecorationLine: 'line-through',
                            color: '#A0A0A0'
                        }]}>{item.oldPrice ? "¥ " + utils.toDecimal2(item.oldPrice) : ""}</Text>
                        <Text
                            style={ShopStyle.listTitleMarkViewText}>{item.nowPrice ? "¥ " + utils.toDecimal2(item.nowPrice) : ""}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        });
        return resultList;
    }


};